package cn.xorange.commons.security.filter.handler;

import cn.xorange.commons.security.constants.SecurityConstants;
import cn.xorange.commons.security.entity.ClaimsInfo;
import cn.xorange.commons.security.entity.SecurityLoginResult;
import cn.xorange.commons.security.entity.SecurityUser;
import cn.xorange.commons.security.exception.SecurityErrorCode;
import cn.xorange.commons.security.filter.FilterHandler;
import cn.xorange.commons.security.service.LoginHandler;
import cn.xorange.commons.security.service.LoginHandlerFactory;
import cn.xorange.commons.security.utils.JwtUtils;
import cn.xorange.commons.security.utils.SecurityUtils;
import cn.xorange.commons.utils.cache.ICacheService;
import cn.xorange.commons.utils.http.ServletUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author : yangjian
 * date : 2024/2/14
 * description :
 */
public class RefreshTokenHandler implements FilterHandler {

    @Resource
    ICacheService cacheService;

    @Resource
    LoginHandlerFactory loginHandlerFactory;

    @Override
    public String url() {
        return SecurityConstants.URL_REFRESH_TOKEN;
    }

    @Override
    public Boolean passToken() {
        return false;
    }

    @Override
    public void handler(HttpServletRequest request, HttpServletResponse response) {
        ClaimsInfo claimsInfo = SecurityUtils.getClaimsInfo();
        if(Objects.nonNull(claimsInfo)){
            String tokenKey = claimsInfo.tokenKey();
            String sysType = claimsInfo.getSysType();
            String loginType = claimsInfo.getLoginType();

            SecurityUser user = cacheService.getCacheObject(tokenKey);

            LoginHandler loginHandler = loginHandlerFactory.getLoginHandler(sysType,loginType);
            if(Objects.isNull(loginHandler) || Objects.isNull(user)){
                SecurityErrorCode code = SecurityErrorCode.AUTH_TOKEN_UNAUTHORIZED;
                ServletUtils.responseOut(response,code.getStatus(),code.getCode(),code.getMsg(),null);
            } else {
                cacheService.expire(tokenKey, loginHandler.config().getTokenExpire());
                String jwtToken = JwtUtils.createJwtToken(sysType, loginType, claimsInfo.getSource(), claimsInfo.getTokenId() , loginHandler.config().getTokenExpire());
                SecurityLoginResult result = new SecurityLoginResult();
                result.setExpiresIn(loginHandler.config().getTokenExpire());
                result.setAccessToken(jwtToken);
                ServletUtils.responseSuccessOut(response, result);
            }
        }
    }
}
